﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace FuncWorks.Xna.UI
{
	public class DynamicTextSize
	{
		List<TextStyle> styles;
		Dictionary<string, Dictionary<float, int>> cache;

		public DynamicTextSize(bool caching)
		{
			styles = new List<TextStyle>();
			cache = caching ? new Dictionary<string, Dictionary<float, int>>() : null;
		}

		// Add text styles in order, large to small
		public void AddTextStyle(TextStyle style)
		{
			styles.Add(style);
		}

		// Returns the height of the string drawn
		public TextStyle GetStyleForTargetSize(string text, float maxWidth)
		{
			// Get info from cache rather than measuring the string again
			if (cache != null)
			{
				if (cache.ContainsKey(text) && cache[text].ContainsKey(maxWidth))
				{
					return styles[cache[text][maxWidth]];
				}
			}

			for (int i = 0; i < styles.Count; i++)
			{
				// Measure string and see if it's under the max
				TextStyle style = styles[i];
				Vector2 size = style.MeasureString(text);
				if (size.X > maxWidth && i < (styles.Count - 1)) { continue; }

				// If caching, add to cache
				if (cache != null)
				{
					if (!cache.ContainsKey(text)) { cache[text] = new Dictionary<float, int>(); }
					cache[text][maxWidth] = i;
				}

				return style;
			}
			return styles[styles.Count - 1];
		}
	}
}
